<?php

/**
* @Name : 登录控制器
* @Function : 
* @Author : Haiwera
* @Created : 2016-11-14
* @Copyright : Haiwera.Fiidee.Monda.Cn
*/
namespace member\service;

use api\utils\PayApiClient;
use api\utils\SaasApiClient;
use herosphp\core\Loader;
use herosphp\core\Log;
use herosphp\session\FileSession;
use herosphp\session\Session;
use herosphp\bean\Beans;
use herosphp\web\WebUtils;
use herosphp\string\StringUtils;
use Symfony\Component\Config\Definition\Exception\Exception;

//	登录控制器
class LoginService{
	
	private $__memberService;

	const SESSION_NAME = 'mpe_member';
    const SIGN_NAME = "dasuinfo";
    const COMPANY   =  "company";
	public function __construct()
	{
		Session::start();	
		$this->__memberService = Beans::get('member.member.service');
	}
	/*
	 * 登录
	 */
	public function login($username,$password)
	{

		$info = $this->__memberService->getItem(array('username' => $username,'del_status'=>0));
		$lastErrorLogin = strtotime($info['last_error_time']);
        if( time() - $lastErrorLogin < 300 ){
            $info['status'] = -1;
            return $info;
        }
        if($info['password'] == passwd($password))
		{
		    if( $info['status'] == "0" ){
		        return $info;
            }
            //存储session
            Session::start();
			session_start();
			
			if($info['dasu_pay_id'])
			{
				$url = "api/user/getUserInfo";
				$result = PayApiClient::send($url, array('userid' => $info['dasu_pay_id']));
				if ( $result->isSucess() ) {
					$items = $result->getItem();
					$_SESSION[self::SESSION_NAME] = array();
					$_SESSION['dasuinfo'] = $items;
				} else {
				    Log::error("登录失败，接口返回：".$result->getMessage());
					//SAAS数据获取失败，登录失败
					return false;
				}
			}
			$session_id = session_id();

			$_SESSION[self::SESSION_NAME] = $info;
            //更新最后登陆ip和登录时间
            $lastLoginTime = date('Y-m-d H:i:s');
            $lastLoginIp = WebUtils::getClientIP();
			$this->__memberService->update(array('last_login_time' => $lastLoginTime, 'last_login_ip' => ip2long($lastLoginIp),'session_id' => $session_id), $info['id']);
            $logService = Beans::get('member.log.service');
            $__data = array(
                'ip'=> $lastLoginIp,
                'addtime'=> $lastLoginTime,
                'name'=> $info['nickname'],
                'username'=> $info['username'],
                'app_id'=> appId(),
            );
            try{
                $logService -> add($__data);
            }catch (Exception $e){
                Log::error("写入会员登陆日志失败:".$e);
            }
			return true;
		}
        Log::error("{$username} 登录失败，账号密码错误");
		return false;
	
	}

	/*
	 * 登出
	 */
	public function logout()
	{
	    //清空登陆的session_id
		session_destroy();
	
	}

	/*
	* 是否登录
	 */
	public function hasLogin()
	{
		$settingService = Beans::get('admin.adminSetting.service');
		$onePointLogin = $settingService->getSetting('onePointLogin');
		if(!isset($_SESSION[self::SESSION_NAME]))
		{
			return false;
		}

		//session_id在后台被干掉了
        $info = $this->__memberService->getItem(array('id'=>$_SESSION[self::SESSION_NAME]['id']));
        if( !$info['session_id'] ){
            $this -> logout();
        }
		//单点登录开启
		if($onePointLogin == 'on'){
			$session_id = session_id();
			//$info = $this->__memberService->getItem(array('id'=>$_SESSION[self::SESSION_NAME]['id']));
			//当前session_id 与最新登录用户session_id 不一致 ，强制下线
			if($info['session_id'] != $session_id){
				$_SESSION = null;
				session_destroy();
				return false;
			}
		}
		$sessionExpr = $settingService->getSetting('sessionExpr');
		if(!$sessionExpr){
			$sessionExpr = 30;
		}
		$prev_op_time = $_SESSION[self::SESSION_NAME]['prev_op_time'] ? $_SESSION[self::SESSION_NAME]['prev_op_time'] : time(0);
		if(!$prev_op_time){ $prev_op_time = time(0); }

		//判断登录是否超时
		if(((time(0) - $prev_op_time) / 60) > $sessionExpr){
			$_SESSION = null;
			session_destroy();	
			return false;
		}
		else{
			$_SESSION[self::SESSION_NAME]['prev_op_time'] = time(0);
		}
        return isset($_SESSION[self::SESSION_NAME]);
	
	}

    /**
     * 设置登陆用户的连续5次登陆错误时间
     * @param $mobile
     */
	public function setLastError($mobile){
	    $service = Beans::get('member.member.service');
        $service -> updates(array('last_error_time'=>myNow()), array("username"=>$mobile,"del_status"=>0));
    }


	/*
	 * 当前用户信息
	 */
	public function getMyInfo()
	{
		return $_SESSION[self::SESSION_NAME];
	}

	public function __get($name)
	{
		if(isset($_SESSION[self::SESSION_NAME][$name]))
		{
			return $_SESSION[self::SESSION_NAME][$name];
		}	
		if(isset($_SESSION[self::SIGN_NAME]) && isset($_SESSION[self::SIGN_NAME][$name]))
		{
			return $_SESSION[self::SIGN_NAME][$name];
		}
        if(isset($_SESSION[self::COMPANY]) && isset($_SESSION[self::COMPANY][$name]))
        {
            return $_SESSION[self::COMPANY][$name];
        }

		return false;
	}
	/**
     * 获取当前用户实名及签约信息
     * @param $key
     * @return bool
     */
	public function getSignInfo($key="")
	{
        if( !$_SESSION[self::SIGN_NAME] ){
            $this -> updateSignInfo();
        }
        if ($key) {
            return $_SESSION[self::SIGN_NAME][$key];
        } else {
            return $_SESSION[self::SIGN_NAME];
        }
	}

    /**
     * 获取公司信息
     * @param null $name
     * @return mixed
     */
	public function getCompany($name = null){

        if( !$_SESSION[self::COMPANY] ){
            $this -> updateCompany();
        }
        if ($name) {
            return $_SESSION[self::COMPANY][$name];
        } else {
            return $_SESSION[self::COMPANY];
        }
    }


	public function update($data)
    {
        $logo_old = $_SESSION[self::SESSION_NAME]['photo'];
        if(isset($data['photo']) && $logo_old != $data['photo'])
        {
            $gcService = Beans::get('admin.gcResource.service');
            $gcService->gc($logo_old,'member','photo',$_SESSION[self::SESSION_NAME]['id']);
        }
        foreach($data as $k => $v)
        {
            $_SESSION[self::SESSION_NAME][$k] = $v;
        }
        return true;
    }

    /**
     * 更新签约信息，如果不传参数，则去SaaS中心获取最新的信息
     * @author LiuYi
     * @param $array
     * @return bool
     */
    public function updateSignInfo($array=null){
        if( is_array($array) ) {
            foreach ($array as $k => $v) {
                $_SESSION[self::SIGN_NAME][$k] = $v;
            }
        }else{
            if($_SESSION[self::SESSION_NAME]['dasu_pay_id'])
            {
                $url = "api/user/getUserInfo";
                $result = PayApiClient::send($url, array('userid' => $_SESSION[self::SESSION_NAME]['dasu_pay_id']));
                if ( $result->isSucess() ) {
                    $items = $result->getItem();
                    $_SESSION[self::SIGN_NAME] = array();
                    $_SESSION[self::SIGN_NAME] = $items;
                } else {
                    Log::error("公司信息获取失败，接口返回：".$result->getMessage());
                }
            }
        }
        return true;
    }

    /**
     * 更新认证公司信息
     * @author LiuYi
     * @param $array | null
     * @return bool
     */
    public function updateCompany( $array=null ){
        if( is_array($array) ){
            foreach($array as $k => $v)
            {
                $_SESSION[self::COMPANY][$k] = $v;
            }
            return true;
        }{
            if($_SESSION[self::SESSION_NAME]['dasu_pay_id'])
            {
                $url = "api/user/getCompanyInfo";
                $result = PayApiClient::send($url, array('userid' => $_SESSION[self::SESSION_NAME]['dasu_pay_id']));
                if ( $result->isSucess() ) {
                    $items = $result->getItem();
                    $main_business = StringUtils::jsonDecode($items['main_business']);
                    $items['main_business'] = $main_business;
                    $types = $this -> getType();
                    $items['main_business_name'] = "";
                    foreach ($types as $value){
                        foreach ( $main_business as $v )
                        if( $value['id'] == $v ){
                            $items['main_business_name'] .= $value['name']. "     ";
                        }
                    }
                    $_SESSION[self::COMPANY] = array();
                    $_SESSION[self::COMPANY] = $items;
                } else {
                    Log::error("获取公司信息失败，接口返回：".$result->getMessage());
                    //SAAS数据获取失败，登录失败
                }
            }
        }
        return true;

    }

    /**
     * 更新企业类别信息
     * @author LiuYi
     * @param $array
     * @return bool
     */
    public function updateType( $array ){
        foreach($array as $k => $v)
        {
            $_SESSION[self::SESSION_NAME]['type'][$k] = $v;
        }
        return true;
    }

    /**
     * 获取企业类别信息
     * @return mixed
     */
    public function getType(){
        if( $_SESSION[self::SESSION_NAME]['type'] ){
            return $_SESSION[self::SESSION_NAME]['type'];
        }else{
            $result = SaasApiClient::send('api/brand/getTypes', array());
            if ($result->isSucess()) {
                $this -> updateType( $result->getData() );
                return $result->getData();
            }
        }
        return null;
    }

}
